package com.hogocloud.corelibrary.common.manager

import android.app.Activity
import android.content.Context
import java.util.*

/**
 * Created by gjc on 2018-05-04.
 *
 *
 * AppManager 管理Activity栈
 */

object AppManager {

    private var activityStack: Stack<Activity>? = null

    val isAppExit: Boolean
        get() = activityStack == null || activityStack?.isEmpty() ?: true

    /**
     * 添加Activity到堆栈
     */
    fun addActivity(activity: Activity) {
        if (activityStack == null) {
            activityStack = Stack()
        }
        activityStack?.add(activity)
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    fun currentActivity(): Activity? {
        return activityStack?.lastElement()
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    fun finishActivity() {
        val activity = activityStack?.lastElement()
        finishActivity(activity)
    }

    /**
     * 结束指定的Activity
     */
    fun finishActivity(activity: Activity?) {
        if (activity != null) {
            activityStack?.remove(activity)
            activity.finish()
        }
    }

    /**
     * 结束指定类名的Activity
     */
    fun finishActivity(cls: Class<*>) {
        activityStack?.let {
            for (activity in it) {
                if (activity.javaClass == cls) {
                    finishActivity(activity)
                }
            }
        }
    }

    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        activityStack?.let {
            var i = 0
            val size = activityStack!!.size
            while (i < size) {
                if (null != activityStack!![i]) {
                    activityStack!![i].finish()
                }
                i++
            }
            activityStack!!.clear()
        }
    }

    /**
     * 退出应用程序
     */
    fun AppExit(context: Context) {
        try {
            finishAllActivity()
            //不杀掉进程
            //            ActivityManager activityMgr =
            //                    (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            //            activityMgr.killBackgroundProcesses(context.getPackageName());
            System.exit(0)
        } catch (e: Exception) {
        }

    }
}
